<template>
  <div class="bird-map-container">
   <div class="main-container">
     <div class="card-header">
       <div class="header-info">
         <h2>2023年中国珍稀鸟类分布</h2>
         <p>数据单位：种</p>
       </div>
     </div>
     <!-- 地图卡片区域 -->
     <div class="map-card">

       <div class="map-container">
         <div ref="mapContainer" class="echarts-map"></div>
         <!-- 数据说明区域 -->
         <div class="data-section">

           <div class="data-card">
             <h3>热点区域</h3>
             <div class="hotspot-list">
               <div class="hotspot-item" v-for="(region, index) in hotspots" :key="index">
                 <div class="rank-badge">{{ index + 1 }}</div>
                 <div class="hotspot-info">
                   <div class="region-name">{{ region.name }}</div>
                   <div class="species-count">{{ region.count }}种珍稀鸟类</div>
                 </div>
               </div>
             </div>
           </div>
         </div>

         <!-- 加载状态 -->
         <div v-if="isLoading" class="loading-indicator">
           <div class="spinner"></div>
           <div class="loading-text">地图加载中...</div>
         </div>

         <!-- 错误提示 -->
         <div v-if="errorMessage" class="error-message">
           <h3>地图加载失败</h3>
           <p>{{ errorMessage }}</p>
           <el-button type="primary" @click="initMap">重试</el-button>
         </div>
       </div>


     </div>
   </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import * as echarts from 'echarts';
import chinaGeoJSON from '@/views/map/json/geojson.json'; // 导入本地GeoJSON文件

// 珍稀鸟类数据
const birdData = ref([
  {name: '北京', value: 235},
  {name: '天津', value: 120},
  {name: '河北', value: 340},
  {name: '山西', value: 215},
  {name: '内蒙古', value: 180},
  {name: '辽宁', value: 285},
  {name: '吉林', value: 170},
  {name: '黑龙江', value: 160},
  {name: '上海', value: 195},
  {name: '江苏', value: 320},
  {name: '浙江', value: 410},
  {name: '安徽', value: 295},
  {name: '福建', value: 430},
  {name: '江西', value: 520},
  {name: '山东', value: 285},
  {name: '河南', value: 240},
  {name: '湖北', value: 395},
  {name: '湖南', value: 480},
  {name: '广东', value: 635},
  {name: '广西', value: 580},
  {name: '海南', value: 425},
  {name: '重庆', value: 310},
  {name: '四川', value: 730},
  {name: '贵州', value: 495},
  {name: '云南', value: 890},
  {name: '西藏', value: 180},
  {name: '陕西', value: 265},
  {name: '甘肃', value: 175},
  {name: '青海', value: 95},
  {name: '宁夏', value: 78},
  {name: '新疆', value: 130}
]);

// 热点区域数据
const hotspots = ref([
  {name: '云南', count: 890},
  {name: '四川', count: 730},
  {name: '广西', count: 580},
  {name: '广东', count: 635},
  {name: '江西', count: 520}
]);


// 响应式状态
const isLoading = ref(true);
const errorMessage = ref(null);
const chartInstance = ref(null);
const mapContainer = ref(null);

// 初始化地图
const initMap = async () => {
  try {
    isLoading.value = true;
    errorMessage.value = null;

    // 确保DOM元素已渲染
    await nextTick();

    if (!mapContainer.value) {
      throw new Error('地图容器未找到');
    }

    // 确保容器有尺寸
    if (mapContainer.value.offsetHeight === 0) {
      mapContainer.value.style.height = '600px';
    }

    // 初始化ECharts实例
    chartInstance.value = echarts.init(mapContainer.value);

    // 使用本地导入的GeoJSON数据
    const geoJson = chinaGeoJSON;

    // 注册地图
    echarts.registerMap('China', geoJson);

    // 创建名称映射表解决名称不匹配问题
    const nameMap = {
      '北京市': '北京',
      '天津市': '天津',
      '河北省': '河北',
      '山西省': '山西',
      '内蒙古自治区': '内蒙古',
      '辽宁省': '辽宁',
      '吉林省': '吉林',
      '黑龙江省': '黑龙江',
      '上海市': '上海',
      '江苏省': '江苏',
      '浙江省': '浙江',
      '安徽省': '安徽',
      '福建省': '福建',
      '江西省': '江西',
      '山东省': '山东',
      '河南省': '河南',
      '湖北省': '湖北',
      '湖南省': '湖南',
      '广东省': '广东',
      '广西壮族自治区': '广西',
      '海南省': '海南',
      '重庆市': '重庆',
      '四川省': '四川',
      '贵州省': '贵州',
      '云南省': '云南',
      '西藏自治区': '西藏',
      '陕西省': '陕西',
      '甘肃省': '甘肃',
      '青海省': '青海',
      '宁夏回族自治区': '宁夏',
      '新疆维吾尔自治区': '新疆',
      '台湾省': '台湾',
      '香港特别行政区': '香港',
      '澳门特别行政区': '澳门'
    };

    // 准备地图数据 - 确保名称匹配
    const mapData = geoJson.features.map(feature => {
      const geoName = feature.properties.name;
      const mappedName = nameMap[geoName] || geoName;

      // 在birdData中查找匹配的数据项
      const dataItem = birdData.value.find(item =>
          item.name === mappedName ||
          item.name.includes(mappedName) ||
          mappedName.includes(item.name)
      );

      return {
        name: geoName, // 使用GeoJSON中的名称确保正确渲染
        value: dataItem ? dataItem.value : 0,
        originalName: dataItem ? dataItem.name : mappedName
      };
    });

    // 设置图表选项
    chartInstance.value.setOption({
      backgroundColor: '#F5FCFF',
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(26, 95, 122, 0.92)',
        borderColor: '#1a5f7a',
        borderWidth: 1,
        padding: [12, 18],
        textStyle: {
          color: '#ffffff',
          fontSize: 14,
          lineHeight: 24
        },
        formatter: function (params) {
          // 直接从mapData中获取值
          const value = params.data?.value ?? 0;
          const name = params.data?.originalName ?? params.name;

          return `
            <div style="font-size:16px; font-weight:bold; margin-bottom:8px;">${name}</div>
            <div style="display:flex; align-items:center; margin-bottom:6px;">
              <div style="width:12px; height:12px; background:${params.color}; border-radius:2px; margin-right:8px;"></div>
              <div>珍稀鸟类: <b>${value}</b> 种</div>
            </div>
            <div style="font-size:13px; margin-top:8px; border-top:1px solid rgba(255,255,255,0.2); padding-top:8px;">
              点击查看详细物种信息
            </div>
          `;
        }
      },
      visualMap: {
        left: 'left',
        top: 'bottom',
        min: 0,
        max: 1000,
        text: ['高', '低'],
        textStyle: {
          color: '#3a5a78'
        },
        calculable: true,
        inRange: {
          color: [
            '#1b5e20',
            '#4caf50',
            '#cddc39',
            '#ff9800',
            '#f44336',
            '#b71c1c'
          ]
        },
        outOfRange: {
          color: '#cfd8dc'
        }
      },
      series: [{
        type: 'map',
        map: 'China',
        roam: true,
        scaleLimit: {
          min: 0.7,
          max: 3
        },
        label: {
          show: true,
          fontSize: 11,
          fontWeight: 'normal',
          formatter: function (params) {
            // 在标签中显示原始名称
            return params.data?.originalName || params.name;
          }
        },
        itemStyle: {
          areaColor: '#d8e7f3',
          borderColor: '#a8c6df',
          borderWidth: 0.8
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 12,
            fontWeight: 'bold',
            formatter: function (params) {
              return params.data?.originalName || params.name;
            }
          },
          itemStyle: {
            areaColor: '#9bc5e0',
            borderColor: '#1a5f7a',
            borderWidth: 1.5
          }
        },
        select: {
          label: {
            fontWeight: 'bold',
            formatter: function (params) {
              return params.data?.originalName || params.name;
            }
          },
          itemStyle: {
            areaColor: '#ffcdd2',
            borderColor: '#f44336'
          }
        },
        data: mapData
      }]
    });

    // 添加点击事件
    chartInstance.value.on('click', (params) => {
      const name = params.data?.originalName || params.name;
      const value = params.data?.value || 0;
      console.log('点击区域:', name, '珍稀鸟类:', value, '种');
    });

    isLoading.value = false;

  } catch (error) {
    console.error('地图初始化失败:', error);
    errorMessage.value = error.message || '地图加载失败，请检查网络连接';
    isLoading.value = false;

    // 清理部分资源
    if (chartInstance.value) {
      chartInstance.value.dispose();
      chartInstance.value = null;
    }
  }
};

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize();
  }
};

// 清理资源
const cleanup = () => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
    chartInstance.value = null;
  }
  window.removeEventListener('resize', handleResize);
};

// 组件挂载时初始化
onMounted(() => {
  // 使用setTimeout确保所有DOM已渲染
  setTimeout(initMap, 50);
  window.addEventListener('resize', handleResize);
});

// 组件卸载前清理
onBeforeUnmount(cleanup);
</script>

<style scoped>
.bird-map-container {
  width: 100%;
  margin: 0 auto;
  background: linear-gradient(135deg, #e0f7fa, #c8e6c9, #a5d6a7);
}

.main-container{
  width: 80%;
  margin: 20px auto;
  overflow: hidden;
  border-radius: 16px;
}

/* 地图卡片区域 */
.map-card {
  background: white;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.12);
  transition: transform 0.4s ease, box-shadow 0.4s ease;
  width: 100%;
  margin: 0 auto;
}

.card-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  margin: 0 auto;
  background: linear-gradient(90deg,
  #0c7b46 0%,
  #2e8b57 25%,
  #3cb371 50%,
  #66cdaa 75%,
  #98fb98 100%
  );
  color: white;
  border-radius: 16px 16px 0 0;
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.12);
}

.header-info h2 {
  font-size: 1.5rem;
  font-weight: 600;
  margin-bottom: 5px;
}

.header-info p {
  font-size: 0.95rem;
  opacity: 0.9;
}

.map-container {
  display: flex;
  width: 100%;
  height: 600px;
  overflow: hidden;
}

.echarts-map {
  width: 77%;
  height: 100%;
}

/* 加载状态 */
.loading-indicator {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.9);
  z-index: 10;
}

.spinner {
  width: 60px;
  height: 60px;
  border: 6px solid rgba(26, 95, 122, 0.2);
  border-radius: 50%;
  border-top-color: #1a5f7a;
  animation: spin 1.2s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.loading-text {
  font-size: 1.1rem;
  color: #1a5f7a;
  font-weight: 500;
}

/* 错误提示 */
.error-message {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 235, 238, 0.9);
  color: #c62828;
  padding: 30px;
  text-align: center;
  z-index: 10;
}

.error-message h3 {
  font-size: 1.5rem;
  margin-bottom: 15px;
}

.error-message p {
  margin-bottom: 20px;
  max-width: 500px;
  line-height: 1.6;
}

/* 数据说明区域 */
.data-card {
  width: 100%;
  height: 600px;
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease;
  z-index: 100;
}


.data-card h3 {
  color: #1a5f7a;
  font-size: 1.3rem;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #e0f7fa;
}

.data-card p {
  color: #455a64;
  line-height: 1.7;
  margin-bottom: 15px;
}

.data-card ul {
  padding-left: 20px;
  margin-top: 15px;
}

.data-card li {
  margin-bottom: 10px;
  color: #546e7a;
  line-height: 1.6;
}

.hotspot-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.hotspot-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #f5f9fa;
  border-radius: 10px;
  transition: background 0.3s ease;
}

.hotspot-item:hover {
  background: #e0f7fa;
}

.rank-badge {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #1a5f7a;
  color: white;
  border-radius: 50%;
  font-weight: bold;
  font-size: 1.1rem;
}

.hotspot-info {
  flex: 1;
}

.region-name {
  font-weight: 600;
  color: #1a5f7a;
  margin-bottom: 5px;
}

.species-count {
  color: #546e7a;
  font-size: 0.95rem;
}

</style>